package juc.toolclass;

import org.junit.Test;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class semaphore {

    /**
     * Semaphore
     */
    @Test
    public void semaphore() {
        Semaphore semaphore=new Semaphore(2);
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                Thread t = Thread.currentThread();
                try {
                    semaphore.acquire();
                    System.out.println(System.currentTimeMillis()+" "+t.getName()+"获取许可");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                    System.out.println(System.currentTimeMillis()+" "+t.getName()+"释放许可");
                }
            });
            thread.setName("t"+i);
            thread.start();
        }
    }

    /**
     * semaphore正确的释放锁的方式
     * @throws InterruptedException
     */
static Semaphore semaphore=new Semaphore(2);
    public static class T extends Thread{

        public T(String name) {
            super(name);
        }

        @Override
        public void run() {
            boolean acquiresuccess=false; //用acquiresuccess来标记线程是否真的获取到了锁
            Thread t = Thread.currentThread();
            try {
                semaphore.acquire();
//                semaphore.tryAcquire();
                acquiresuccess=semaphore.tryAcquire(1,TimeUnit.SECONDS);
                if(acquiresuccess){
                    System.out.println(System.currentTimeMillis()+" "+t.getName()+"获取许可,当前可用许可证数量"+semaphore.availablePermits());
                    TimeUnit.SECONDS.sleep(4);
                    System.out.println(System.currentTimeMillis()+" "+t.getName()+" 运行结束");

                }else {
                    System.out.println(System.currentTimeMillis()+" "+t.getName()+"获取失败,当前可用许可证数量"+semaphore.availablePermits());
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if(acquiresuccess){
                    semaphore.release();
                }
            }
        }
    }
    @Test
    public void semaphore1() throws InterruptedException {
        T t1 = new T("t1");
        t1.start();
        TimeUnit.SECONDS.sleep(1);

        T t2 = new T("t2");
        t2.start();
        TimeUnit.SECONDS.sleep(1);

        T t3 = new T("t3");
        t3.start();
        }
}
